package com.zhangbaiyan.test2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author zhangbaiyan
 * @date 2024-09-25 23:46
 * @description:
 * @version:
 */
public class receive {
    public static void main(String[] args) throws IOException {
        //接收数据


        //1.创建DatagramSocket对象(快递公司)
        //细节:
        //再接收的时候,一定要绑定端口
        //而且绑定的端口一定要更发送的端口一致
        DatagramSocket ds = new DatagramSocket(8080);

        //2.接收数据包
        byte[] bytes = new byte[1024];

        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
        System.out.println("等待接收数据");
        ds.receive(dp);
        System.out.println("接收到数据");

        //3,解析数据包
        byte[] data = dp.getData();
        int len = dp.getLength();
        InetAddress address = dp.getAddress();
        String str = new String(data, 0, len);
        int port = dp.getPort();

        System.out.println("接收到数据"+str);
        System.out.println("该数据是从"+address+"来自"+port+"端口");

        //释放资源
        ds.close();
    }
}
